package com.tude._07vehicle.controller;

import com.tude._07vehicle.base.response.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
//  ***********   最终目标:    d:/files/2025/4/16/全局唯一的文件名.jpg    ***********
@Api(tags = "04.文件上传")
@Slf4j
@RestController
@RequestMapping("v1/file/")
public class UploadController {
    @ApiOperation("文件上传")
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        // 原始文件名字
        String filename = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        // 生成一个全球唯一的随机字符串,作为新的文件名
        filename = UUID.randomUUID() + suffix;
        log.info("文件上传:{}", filename);

        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());

        String staticPath = "c:/files";
        // 创建目录
        File dirPath = new File(staticPath + datePath);
        if (!dirPath.exists()){
            dirPath.mkdirs();
        }
        // 保存文件
        String filePath = staticPath + datePath + filename;
        file.transferTo(new File(filePath));

        return JsonResult.ok(datePath + filename);
    }
}
